using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Validation.Configuration;
using System.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using System.IO;

namespace EntLibContrib.Validation.Configuration
{
    [ConfigurationElementType(typeof(ExternallyConfiguredObjectValidatorData))]
    public class ExternallyConfiguredObjectValidatorData : ValidatorData
    {
        public ExternallyConfiguredObjectValidatorData()
        { }


        protected ExternallyConfiguredObjectValidatorData(string name, Type type)
            :base(name, type)
        {
        }

        public ExternallyConfiguredObjectValidatorData(string name)
            :base(name, typeof(ExternallyConfiguredObjectValidator))
        {
            Name = name;
        }

        private const string TargetRulesetPropertyName = "targetRuleset";
        
        [ConfigurationProperty(TargetRulesetPropertyName)]
        public string TargetRuleset
        {
            get { return (string)this[TargetRulesetPropertyName]; }
            set { this[TargetRulesetPropertyName] = value; }
        }

        private const string TargetConfigurationFilePropertyName = "targetConfigFile";
        
        [ConfigurationProperty(TargetConfigurationFilePropertyName, IsRequired=true)]
        public string TargetConfigurationFile
        {
            get { return (string)this[TargetConfigurationFilePropertyName]; }
            set { this[TargetConfigurationFilePropertyName] = value; }
        }

        protected override Microsoft.Practices.EnterpriseLibrary.Validation.Validator DoCreateValidator(Type targetType)
        {
            if (!File.Exists(TargetConfigurationFile)) throw new ConfigurationErrorsException(Resources.ExternalConfigurationFileNotFound);

            return new ExternallyConfiguredObjectValidator(TargetRuleset, TargetConfigurationFile);
        }
    }
}
